package 程序员面试金典;

import java.util.Stack;

public class 计算器 {

    public int calculate(String s) {
        if (s==null || s.equals(" "))
            return 0;
        Stack<Integer> stack = new Stack<>();
        int num=0;
        char opt='+';
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c))
                num=num*10+(c-'0');
            if ((!Character.isDigit(c) && c!=' ') || i==s.length()-1){
                switch (opt){
                    case '+': stack.push(num);break;
                    case '-': stack.push(-num);break;
                    case '*': stack.push(stack.pop()*num);break;
                    case '/': stack.push(stack.pop()/num);break;
                }
                num=0;
                opt = c;
            }
        }
        int res=0;
        while (!stack.isEmpty()){
            res+=stack.pop();
        }
        return res;
    }
}
